//
//  LLPublishViewController.m
//  LoveLove
//
//  Created by wkf on 2019/3/27.
//  Copyright © 2019 wkf. All rights reserved.
//

#import "LLPublishViewController.h"
#import "AppDelegate.h"
#import "TZImagePickerController.h"
#import "LLCourseTitleTableViewCell.h"
#import "LLPublish2ViewController.h"
#import "UpImageTools.h"
#import "LLPublishCatoryVC.h"

@interface LLPublishViewController ()<UINavigationControllerDelegate,LLCourseTitleTableViewCellDelegate,TZImagePickerControllerDelegate>
@property (strong, nonatomic) UITextView *courseNameTxt;//课程名称文本
@property (strong, nonatomic) UITextView *bodyTitleTxt;//课程正文文本
@property (strong, nonatomic) UIView *bgview1;//
@property (assign, nonatomic) NSInteger maxImgCount;//可上传图片的最大数
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *neirong;
@property (copy, nonatomic) NSString *outputPath;
@property (copy, nonatomic) NSString *type;
@property (strong, nonatomic) NSMutableArray *imgaeUrlArray;
@property (strong, nonatomic) NSMutableArray *imgaeUrlArray1;

@property (nonatomic,assign) BOOL isVideo;
@end

@implementation LLPublishViewController

-(NSMutableArray *)imgaeUrlArray1{
    if (!_imgaeUrlArray1) {
        _imgaeUrlArray1 = [NSMutableArray array];
    }
    return _imgaeUrlArray1;
}

- (void)viewWillAppear:(BOOL)animated {
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [super viewWillAppear:animated];
    [SVProgressHUD dismiss];
    self.navigationController.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //TODO: 页面Disappear 启用
    [[IQKeyboardManager sharedManager] setEnable:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self titleView];
    self.titleLabel.text = @"发 布";
    [self.leftButton setTitle:@"取消" forState:0];
    [self.leftButton setImage:nil forState:0];
    self.leftButton.frame = CGRectMake(20, self.navH-33, 80, 18);
    [self.leftButton setTitleColor:LLColorRGB(0) forState:0];
    self.leftButton.titleLabel.font = LLRegularFont(17);
    [self.rightButton setTitle:@"下一步" forState:0];
    [self.rightButton setTitleColor:LLColor(249, 1, 0) forState:0];
    self.rightButton.titleLabel.font = LLRegularFont(17);
    self.rightButton.frame = CGRectMake(LLScreenWidth-100, self.navH-33, 80, 18);
    self.leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    self.rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, LLScreenHeight-40, LLScreenWidth, 40)];
    bgView.backgroundColor = LLColorRGB(243);
    [self.view addSubview:bgView];
    
    LLButton *button = [LLInitBaseViewTool buttonWithTitle:nil image:@"Picture_162.68387096774px_1190943_easyicon.net" titleColor:nil font:0];
    button.frame = CGRectMake(bgView.width-48, 8, 28, 22);
    button.tag = 1;
    [button addTarget:self action:@selector(didSelectType:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:button];
    LLButton *button1 = [LLInitBaseViewTool buttonWithTitle:nil image:@"video_camera_128px_1230619_easyicon.net" titleColor:nil font:0];
    button1.frame = CGRectMake(bgView.width-48-53, 8, 28, 22);
    button1.tag = 2;
    [button1 addTarget:self action:@selector(didSelectType:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:button1];
    
    self.imgaeUrlArray = [NSMutableArray array];
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:[LLUserDefaults objectForKey:@"imgaeUrlArray"]];
      NSArray *array1 = [NSKeyedUnarchiver unarchiveObjectWithData:[LLUserDefaults objectForKey:@"imgaeUrlArray1"]];
    [self.imgaeUrlArray addObjectsFromArray:array];
     [self.imgaeUrlArray1 addObjectsFromArray:array1];
    self.type = [LLUserDefaults objectForKey:@"type"];
    self.name = [LLUserDefaults objectForKey:@"name"];
    self.neirong = [LLUserDefaults objectForKey:@"neirong"];
    self.outputPath = [LLUserDefaults objectForKey:@"outputPath"];
    self.maxImgCount = 3-self.imgaeUrlArray.count;
    [self showbgview1];
    // Do any additional setup after loading the view.
}

#pragma mark - 显示视图操作方法
- (void)configTableView {
    self.needRefresh = NO;
    [super configTableView];
    self.tableView.backgroundColor = LLColorRGB(255);
    self.tableView.top = self.navH;
    self.tableView.mj_h = LLScreenHeight-self.navH-240;
    [self.tableView registerCellByClassName:@"LLCourseTitleTableViewCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LLCourseTitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LLCourseTitleTableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.tableView = tableView;
    if (indexPath.section == 0) {
        self.courseNameTxt = cell.textView;
        cell.contentStr = self.name;
    } else {
        UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LLScreenWidth, 0.5)];
        lineview.backgroundColor = LLColorRGB(243);
        [cell addSubview:lineview];
        self.bodyTitleTxt = cell.textView;
        cell.contentStr = self.neirong;
        cell.placeholder = @"请输入内容";
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        LLCourseTitleTableViewCell * cell = (LLCourseTitleTableViewCell *)[tableView.dataSource tableView:self.tableView cellForRowAtIndexPath:indexPath];
        return [cell CellHeight];
    } else {
        LLCourseTitleTableViewCell * cell = (LLCourseTitleTableViewCell *)[tableView.dataSource tableView:self.tableView cellForRowAtIndexPath:indexPath];
        if ([cell CellHeight]>100) {
             return [cell CellHeight];
        } else {
             return 100;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0000001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0000001;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}



- (void)updatedText:(NSString *)text atIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        self.courseNameTxt.text = text;
        self.name = text;
    } else {
        self.bodyTitleTxt.text = text;
        self.neirong = text;
    }
}
#pragma mark - 左上角的信息动作点击事件
- (void)didButtonWithleftButton{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        
    }];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"保存草稿" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        [LLUserDefaults setObject:self.name forKey:@"name"];
        NSData * data  = [NSKeyedArchiver archivedDataWithRootObject:self.imgaeUrlArray];
        NSData * data1  = [NSKeyedArchiver archivedDataWithRootObject:self.imgaeUrlArray1];
        [LLUserDefaults setObject:data forKey:@"imgaeUrlArray"];
        [LLUserDefaults setObject:self.type forKey:@"type"];
        [LLUserDefaults setObject:self.outputPath forKey:@"outputPath"];
        [LLUserDefaults setObject:self.neirong forKey:@"neirong"];
        [LLUserDefaults setObject:data1 forKey:@"imgaeUrlArray1"];
        [self dismissViewControllerAnimated:NO completion:^{
            AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            TabBarViewController *tab = (TabBarViewController *)delegate.window.rootViewController;
            tab.selectedIndex = self.selectedindex;
        }];
    }];
    UIAlertAction *picture = [UIAlertAction actionWithTitle:@"不保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [LLUserDefaults setObject:nil forKey:@"name"];
        [LLUserDefaults setObject:nil forKey:@"imgaeUrlArray"];
        [LLUserDefaults setObject:nil forKey:@"type"];
        [LLUserDefaults setObject:nil forKey:@"outputPath"];
        [LLUserDefaults setObject:nil forKey:@"neirong"];
         [LLUserDefaults setObject:nil forKey:@"imgaeUrlArray1"];
        [self dismissViewControllerAnimated:NO completion:^{
            AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            TabBarViewController *tab = (TabBarViewController *)delegate.window.rootViewController;
            tab.selectedIndex = self.selectedindex;
        }];
    }];
    [alertVc addAction:cancle];
    [alertVc addAction:camera];
    [alertVc addAction:picture];
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark - 右上角的动作点击事件
- (void)didButtonWithrightButton{
    if (self.name.length == 0) {
         [self showSVProgressHUDInfoWithsStatus:@"请输入标题"];
    }else if (self.imgaeUrlArray.count == 0 && self.neirong.length == 0){
         [self showSVProgressHUDInfoWithsStatus:@"请至少输入正文或者插入图片"];
    }else{
        LLPublishCatoryVC *vc = [LLPublishCatoryVC new];
        vc.name = self.name;
        vc.conent = self.neirong;
        vc.imageArr = self.imgaeUrlArray1.copy;
        vc.type = self.type.integerValue;
        vc.isVideo = self.isVideo;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
 
}

- (void)didSelectType:(LLButton *)button{
    //照片
    if (button.tag == 1) {
        if (self.type.integerValue == 1) {
            [self showSVProgressHUDInfoWithsStatus:@"您已经选择了视频"];
            [SVProgressHUD dismissWithDelay:1];
            return;
        }
        if (self.imgaeUrlArray.count < 3) {
            if ([CommonTools albumAuthority] == NO) {
                [self showSVProgressHUDInfoWithsStatus:@"您还未打开相册权限~"];
            } else {
                TZImagePickerController *vc = [[TZImagePickerController alloc] initWithMaxImagesCount:8 delegate:self];
                vc.naviBgColor = LLColor(231, 0, 0);
                // 去除毛玻璃效果
                vc.navigationBar.translucent = NO;
                vc.allowPickingVideo = NO;
                vc.allowTakePicture = NO;
                vc.maxImagesCount = self.maxImgCount;
                [self presentViewController:vc animated:YES completion:nil];
            }
        } else {
            [self showSVProgressHUDInfoWithsStatus:@"最多只能显示3张照片"];
            [SVProgressHUD dismissWithDelay:1];
        }
    }
    //视频
    else {
        if (self.type.integerValue == 2) {
            [self showSVProgressHUDInfoWithsStatus:@"您已经选择了图片"];
            [SVProgressHUD dismissWithDelay:1];
            return;
        }
        if (self.imgaeUrlArray.count == 0) {
            if ([CommonTools albumAuthority] == NO) {
                [self showSVProgressHUDInfoWithsStatus:@"您还未打开相册权限~"];
                [SVProgressHUD dismissWithDelay:1];
            } else {
                TZImagePickerController *vc = [[TZImagePickerController alloc] initWithMaxImagesCount:8 delegate:self];
                vc.naviBgColor = LLColor(231, 0, 0);
                // 去除毛玻璃效果
                vc.navigationBar.translucent = NO;
                vc.allowPickingOriginalPhoto = NO;
                // 是否允许显示视频
                vc.allowPickingVideo = YES;
                // 是否允许显示图片
                vc.allowPickingImage = NO;
                vc.allowTakeVideo = NO;
                vc.maxImagesCount = 1;
                [self presentViewController:vc animated:YES completion:nil];
            }
        } else {
            [self showSVProgressHUDInfoWithsStatus:@"请先删除所选的视频或图片"];
        }
    }
}

#pragma mark --- TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    self.type = @"2";
    [self.imgaeUrlArray addObjectsFromArray:photos];
    self.maxImgCount = self.maxImgCount-photos.count;
    [self.bgview1 removeFromSuperview];
    [self showbgview1];
    for (UIImage *image1 in photos) {
         [self upImage:image1];
    }
//     NSData *imagedata = UIImagePNGRepresentation(image);
   
}
// 选择视频的回调
-(void)imagePickerController:(TZImagePickerController *)picker
       didFinishPickingVideo:(UIImage *)coverImage
                sourceAssets:(PHAsset *)asset{
    self.type = @"1";
  
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset completion:^(NSString *outputPath) {
        self.outputPath = outputPath;
       
        NSInteger size = [self getVideoInfoWithSourcePath:outputPath];
        if (size > 50) {
             [self showSVProgressHUDInfoWithsStatus:@"视频不能超过50M"];
            return ;
        }
         self.isVideo = YES;
        [self upVideo:outputPath];
          [self.imgaeUrlArray addObject:coverImage];
        [self.bgview1 removeFromSuperview];
        [self showbgview1];
      
    }];
   
   
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

- (void)dealloc {
    self.navigationController.delegate = nil;
    [LLNotificationCenter removeObserver:self];
}

#pragma mark - 加载图片视频页面
-(void)showbgview1{
    [self.bgview1 removeFromSuperview];
    self.bgview1 = [[UIView alloc] initWithFrame:CGRectMake(0, LLScreenHeight-240, LLScreenWidth, 200)];
    self.bgview1.backgroundColor = LLColorRGB(255);
    [self.view addSubview:self.bgview1];
    
    if (self.type.integerValue == 2) {
        for (int i=0; i<self.imgaeUrlArray.count; i++) {
            UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10*i+20+(LLScreenWidth-60)/3*i, 100, (LLScreenWidth-60)/3, 85)];
            imageview.image = self.imgaeUrlArray[i];
            imageview.layer.masksToBounds = YES;
            imageview.layer.cornerRadius = 4;
            [self.bgview1 addSubview:imageview];
            imageview.contentMode = UIViewContentModeScaleAspectFill;
            
            UIButton *cancle = [LLInitBaseViewTool buttonWithTitle:nil image:@"矩形 5 拷贝 6" titleColor:nil font:0];
            cancle.tag = i;
            cancle.frame = CGRectMake(imageview.mj_x+(LLScreenWidth-60)/3-10, 90, 20, 20);
            [cancle addTarget:self action:@selector(didSelectCancle:) forControlEvents:UIControlEventTouchUpInside];
            [self.bgview1 addSubview:cancle];
        }
    } else if (self.type.integerValue == 1) {
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, LLScreenWidth-40, 180)];
        imageview.image = self.imgaeUrlArray[0];
        imageview.layer.masksToBounds = YES;
        imageview.layer.cornerRadius = 4;
        [self.bgview1 addSubview:imageview];
         imageview.contentMode = UIViewContentModeScaleAspectFill;
        
        UIImageView *imageview1 = [[UIImageView alloc] initWithFrame:CGRectMake(imageview.width/2-35/2, imageview.height/2-35/2, 35, 35)];
        imageview1.image = [UIImage imageNamed:@"多边形 1559"];
        [imageview addSubview:imageview1];
         imageview1.contentMode = UIViewContentModeScaleAspectFill;
        
        UIButton *cancle = [LLInitBaseViewTool buttonWithTitle:nil image:@"矩形 5 拷贝 6" titleColor:nil font:0];
        cancle.tag = 0;
        cancle.frame = CGRectMake(LLScreenWidth-30, 0, 20, 20);
        [cancle addTarget:self action:@selector(didSelectCancle:) forControlEvents:UIControlEventTouchUpInside];
        [self.bgview1 addSubview:cancle];
    }

}

#pragma mark - 删除图片
-(void)didSelectCancle:(LLButton *)button{
    self.maxImgCount ++;
    [self.imgaeUrlArray removeObjectAtIndex:button.tag];
    self.type = @"2";
    [self showbgview1];
}


#pragma mark--- 上传视频

-(void)upImage:(UIImage *)image{
//    LLUserInfo *user = [LLUserInfo sharedUser];
//   NSDictionary *dic = @{@"edu_id":@"8",@"user_id":user.user_id,@"user_random":user.user_random};

   
//    [LLHttpTool post:LLHOST headParams:nil params:dic success:^(NSDictionary *result) {
//
//
//    } failure:^(NSString *msg) {
//        [SVProgressHUD showErrorWithStatus:msg];
//
//    }];
    [UpImageTools upLoadImage:image success:^(NSString * _Nonnull url) {
        NSLog(@"url--%@",url);
        [self.imgaeUrlArray1 addObject:url];
    } failure:^(NSString * _Nonnull errorString) {
        [SVProgressHUD showErrorWithStatus:errorString];
    }];
    
    
    
}
-(void)upVideo:(NSString *)filePath{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UpImageTools asyncUploadVideo:filePath success:^(NSString * _Nonnull url) {
            NSLog(@"url--%@",url);
            [self.imgaeUrlArray1 addObject:url];
        } failure:^(NSString * _Nonnull errorString) {
            [SVProgressHUD showErrorWithStatus:errorString];
        }];
    });
   
    
}

/**
 * @method
 *
 * @brief 根据路径获取视频时长和大小
 * @param path       视频路径
 * @return    字典    @"size"－－文件大小   @"duration"－－视频时长
 */

- (NSInteger )getVideoInfoWithSourcePath:(NSString *)path{
    AVURLAsset * asset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:path]];
    CMTime   time = [asset duration];
    int seconds = ceil(time.value/time.timescale);
    
    NSInteger   fileSize = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil].fileSize;
    
    return fileSize/(1024.0*1024.0);
}

/*ni
 
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
